package com.starsoft.trade.web;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.starsoft.frame.base.bean.BaseAcount;
import com.starsoft.frame.base.plugin.AcountPluginService;
import com.starsoft.frame.base.service.AcountService;
import com.starsoft.frame.core.web.WebUtil;
import com.starsoft.frame.util.StringUtil;
import com.starsoft.trade.bean.TradeAcount;
import com.starsoft.trade.service.TradeAcountService;
import com.starsoft.trade.trader.TraderService;

@RestController
@RequestMapping(value = "/trade/set")
public class TradeAcountController {

	private static Logger logger = LoggerFactory.getLogger(TradeAcountController.class);
	
	@Autowired
	private TradeAcountService tradeAcountService;
	
	@Autowired
	private TraderService traderService;
	
	@Autowired
	private AcountPluginService acountPluginService;
	
	@Autowired
	private AcountService acountService;
	
	@RequestMapping(value="/getacount")
	public TradeAcount getacount(BaseAcount acount){
		return tradeAcountService.get(acount.getAcountId());
	}
	
	@RequestMapping(value="/saveacount")
	public Map<String, Object> saveInitStatus(TradeAcount tradeAcount, HttpServletRequest request){
		tradeAcountService.saveOrUpdate(tradeAcount);
		Integer acountId = tradeAcount.getAcountId();
		acountPluginService.update(acountService.getAcount(acountId));
		return WebUtil.sucesseModel("保存成功");
	}
	
	@RequestMapping(value="/extest")
	public Map<String, Object> testExTrader(BaseAcount acount) {
		TradeAcount tradeAcount = tradeAcountService.get(acount.getAcountId());
		String exSystem = tradeAcount.getExSystem();
		if(StringUtil.isEmpty(exSystem)){
			return WebUtil.sucesseModel("未配置交易接口");
		}
		
		try {
			traderService.getPortfoil(tradeAcount);
			return WebUtil.sucesseModel("接口测试通过");
		} catch (Exception e) {
			logger.error("接口测试失败:", e);
			return WebUtil.errorModel("接口测试失败:\n" + e.getMessage());
		}
	}
}
